/**
 * 
 */
package masterlink.futures.listener;

import java.util.Enumeration;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import masterlink.futures.controller.AdminController;

import org.slf4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import baytony.util.log.Log;

/**
 * @author tonyyang
 *
 */
public class SessionListener implements HttpSessionListener {
	
	private static final Logger log=Log.getLogger(SessionListener.class);
	private static final String WEB_APPLICATION_CONTEXT="org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcherServlet";
	
	public SessionListener() {
		log.trace("{} loaded!",this.getClass().getName());
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionListener#sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		getAdminController(se).addSession(se.getSession());
	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpSessionListener#sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		getAdminController(se).removeSession(se.getSession());
	}
	
	private AdminController getAdminController(HttpSessionEvent se){
		//logAll(se.getSession().getServletContext());
		WebApplicationContext ctx = (WebApplicationContext)se.getSession().getServletContext().getAttribute(WEB_APPLICATION_CONTEXT);
		return ctx.getBean(AdminController.class);
	}
	
	private void logAll(ServletContext c){
		Enumeration<String> e= c.getAttributeNames();
		while(e.hasMoreElements()){
			String name=e.nextElement();
			log.debug("{} : {}",name,c.getAttribute(name).getClass().getName());
		}
	}

}
